package org.jetnuke.dao.generic;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.dao.generic.AutoKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.entities.BlogCategory;

public class GenericBlogCategoryDAO extends AutoKeys implements
		org.jetnuke.dao.BlogCategoryDAO {

	public BlogCategory retrieveByPK(int id) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("BlogCategoryModel.selectByID"));
		p.setInt(1, id);
		
		ResultSet rs = p.executeQuery();
		BlogCategory s = new BlogCategory();
		
		if (rs.next()) {
			fillBlogCategoryFromResultSet(s, rs);
		}
		
		rs.close();
		p.close();

		return s;
	}
	
	protected void fillBlogCategoryFromResultSet(BlogCategory s, ResultSet rs) throws Exception{
		s.setAID(rs.getInt("AID"));
		s.setDESCRIPTION(rs.getString("DESCRIPTION"));
		s.setID(rs.getInt(("ID")));
		s.setNAME(rs.getString("NAME"));
		s.setPARENTID(rs.getInt("PID"));
	}

	public void update(BlogCategory bp) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("BlogCategoryModel.update"));
		p.setInt(1,bp.getAID());
		p.setString(2,bp.getNAME());
		p.setString(3,bp.getDESCRIPTION());
		p.setInt(4,bp.getPARENTID());
		p.setInt(5,bp.getID());
		p.executeUpdate();
		p.close();

	}

	public int addNew(BlogCategory bp) throws Exception {
		PreparedStatement p = this.getStatementForAutoKeys("BlogCategoryModel.addNew");
		this.setAutoGeneratedKeysQuery(SystemGlobals.getSql("BlogCategoryModel.lastGeneratedBlogCategoriesID"));
		initBlogCategory(bp, p);
		
		int id = this.executeAutoKeysQuery(p);
		p.close();		
		return id;
	}

	protected void initBlogCategory(BlogCategory bp, PreparedStatement p) throws Exception{
		p.setInt(1,bp.getAID());
		p.setString(2,bp.getNAME());
		p.setString(3,bp.getDESCRIPTION());
		p.setInt(4,bp.getPARENTID());
		
	}

	public List selectByUser(int uid) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("BlogCategoryModel.selectByUser"));
		p.setInt(1,uid);	
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();
		
		return list;
	}

	protected List processSelectAll(ResultSet rs) throws Exception{
		List list = new ArrayList();
		while (rs.next()) {
			BlogCategory u = new BlogCategory();
			fillBlogCategoryFromResultSet(u,rs);			
			list.add(u);
		}
		return list;
	}

	public void deleteCategory(int id) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("BlogCategoryModel.delete"));
		p.setInt(1,id);
		p.executeUpdate();
		p.close();
		
	}

}
